<template>
  <div>
    <!-- 筛选条件 -->
    <div class="filter">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.value }"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }} <span v-if="tab.count !== null">{{ tab.count }}</span>
      </button>
      <button class="create-button" @click="createNewNotice">+ 新建通知</button>
    </div>

    <!-- 富文本编辑器区域 -->
    <div v-if="showEditor" class="editor-container">
      <input
        type="text"
        v-model="newNotice.title"
        placeholder="请输入标题，最多60个字符"
        maxlength="60"
        class="title-input"
      />
      <!-- 使用 Quill 编辑器 -->
      <QuillEditor v-model="newNotice.content" />
      
      <div class="publish-options">
        <label>发布方式：</label>
        <input type="radio" id="unified" value="1" v-model="newNotice.type" @change="handlePublishTypeChange" />
        <label for="unified">统一发布</label>
        <input type="radio" id="division" value="2" v-model="newNotice.type" @change="handlePublishTypeChange" />
        <label for="division">分班发布</label>
        
        <!-- 分班选择复选框 -->
        <div v-if="newNotice.type === '2'" class="division-checkboxes">
          <label v-for="division in divisionList" :key="division.division_id" class="division-checkbox-label">
            <input type="checkbox" :value="division.division_id" v-model="selectedDivisions" />
            {{ division.division_name }}
          </label>
        </div>
      </div>
      <div class="editor-actions">
        <button @click="cancelEdit" class="cancel-button">取消</button>
        <button @click="submitNotice" class="submit-button">{{ isEditing ? '更新' : '提交' }}</button>
      </div>
    </div>

    <!-- 通知列表 -->
    <div
      v-for="notification in paginatedNotifications"
      :key="notification.notice_id"
      class="notification-card"
      @mouseenter="notification.showActions = true"
      @mouseleave="notification.showActions = false"
    >
      <div class="notification-header">
        <span
          class="badge"
          :class="notification.notice_type === 1 ? 'badge-unified' : 'badge-division'"
        >
          {{ notification.typeLabel }}
        </span>
        <h2>{{ notification.notice_title }}</h2>

        <!-- 编辑和删除按钮 -->
        <div v-show="notification.showActions" class="notification-actions">
          <button @click="editNotification(notification)" class="edit-button">编辑</button>
          <button @click="deleteNotification(notification.notice_id)" class="delete-button">删除</button>
        </div>
      </div>
      <p style="margin-left:10%" v-html="notification.notice_content"></p>
      <!-- 如果是分班发布，显示分班名称 -->
      <div v-if="notification.notice_type === 2" style="margin-left:10%" class="division-labels">
        <span v-for="division in notification.divisions" :key="division.division_id" class="division-name">
          {{ division.division_name }}
        </span>
      </div>
    </div>

    <!-- 分页组件 -->
    <PagiNation
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="handlePageChange"
    />
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { fetchNotices, createNotice, fetchDivisionList, updateNotice, deleteNotice } from '@/services/api'; // 引入API
import PagiNation from '@/components/PagiNation.vue'; // 引入分页组件
import QuillEditor from '@/components/QuillEditor.vue'; // 引入 Quill 编辑器组件

export default {
  name: 'TechNoti',
  components: {
    PagiNation, // 注册分页组件
    QuillEditor, // 注册 Quill 编辑器组件
  },
  props: {
    classId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const showEditor = ref(false);
    const isEditing = ref(false);
    const currentTab = ref('全部通知');
    const currentPage = ref(1);
    const itemsPerPage = 8;

    const tabs = ref([
      { label: '全部通知', value: '全部通知', count: null },
      { label: '统一发布', value: 1, count: null },
      { label: '分班发布', value: 2, count: null },
    ]);
    const notifications = ref([]);
    const divisionList = ref([]);
    const selectedDivisions = ref([]);

    const newNotice = ref({
      notice_id: null, // 存储公告ID，用于编辑
      title: '',
      content: '',
      type: '1',
    });

    const loadNotices = async () => {
      try {
        const response = await fetchNotices(props.classId);
        if (response.data.status === 1) {
          notifications.value = response.data.data.map((notice) => ({
            ...notice,
            typeLabel: notice.notice_type === 1 ? '统一发布' : '分班发布',
            showActions: false,
          }));

          // 更新每个类型的数量
          tabs.value.forEach((tab) => {
            if (tab.value === '全部通知') {
              tab.count = notifications.value.length;
            } else {
              tab.count = notifications.value.filter(
                (notice) => notice.notice_type === tab.value
              ).length;
            }
          });
        } else {
          console.error('获取通知公告失败，错误信息:', response.data.msg);
        }
      } catch (error) {
        console.error('加载通知公告失败:', error);
      }
    };

    const loadDivisionList = async () => {
      try {
        const response = await fetchDivisionList(props.classId);
        if (response.data.status === 1) {
          divisionList.value = response.data.data;
        } else {
          console.error('获取分班列表失败，错误信息:', response.data.msg);
        }
      } catch (error) {
        console.error('加载分班列表失败:', error);
      }
    };

    const handlePublishTypeChange = () => {
      if (newNotice.value.type === '2') {
        loadDivisionList();
      }
    };

    const filteredNotifications = computed(() => {
      if (currentTab.value === '全部通知') {
        return notifications.value;
      } else {
        return notifications.value.filter(
          (notification) => notification.notice_type === currentTab.value
        );
      }
    });

    const paginatedNotifications = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredNotifications.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredNotifications.value.length / itemsPerPage);
    });

    const changeTab = (tabValue) => {
      currentTab.value = tabValue;
      currentPage.value = 1;
    };

    const createNewNotice = () => {
      showEditor.value = true;
      isEditing.value = false;
      resetNoticeForm();
    };

    const editNotification = (notification) => {
      showEditor.value = true;
      isEditing.value = true;
      newNotice.value = {
        notice_id: notification.notice_id,
        title: notification.notice_title,
        content: notification.notice_content,
        type: notification.notice_type.toString(),
      };
      selectedDivisions.value = notification.notice_type === 2 ? notification.divisions.map(d => d.division_id) : [];
    };

    const submitNotice = async () => {
      try {
        if (!newNotice.value.title || !newNotice.value.content) {
          console.error('通知标题或内容不能为空');
          return;
        }

        const payload = {
          semester_id: props.classId,
          notice_title: newNotice.value.title.trim(),
          notice_content: newNotice.value.content.trim(),
          division_ids: newNotice.value.type === '2' ? selectedDivisions.value : null,
        };

        if (isEditing.value) {
          // 编辑模式
          payload.notice_id = newNotice.value.notice_id;
          const response = await updateNotice(payload);
          if (response.data.status === 1) {
            console.log('通知更新成功');
            showEditor.value = false;
            loadNotices();
          } else {
            console.error('更新通知失败:', response.data.msg);
          }
        } else {
          // 新建模式
          const response = await createNotice(payload);
          if (response.data.status === 1) {
            console.log('通知发布成功');
            showEditor.value = false;
            loadNotices();
          } else {
            console.error('发布通知失败:', response.data.msg);
          }
        }
      } catch (error) {
        console.error('操作失败:', error.response ? error.response.data : error.message);
      }
    };

    const deleteNotification = async (noticeId) => {
      try {
        const response = await deleteNotice(noticeId);
        if (response.data.status === 1) {
          console.log('通知删除成功');
          loadNotices();
        } else {
          console.error('删除通知失败:', response.data.msg);
        }
      } catch (error) {
        console.error('删除通知失败:', error.response ? error.response.data : error.message);
      }
    };

    const cancelEdit = () => {
      showEditor.value = false;
      resetNoticeForm();
    };

    const resetNoticeForm = () => {
      newNotice.value = {
        notice_id: null,
        title: '',
        content: '',
        type: '1',
      };
      selectedDivisions.value = [];
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    onMounted(() => {
      loadNotices();
    });

    return {
      showEditor,
      isEditing,
      currentTab,
      tabs,
      currentPage,
      totalPages,
      notifications,
      newNotice,
      filteredNotifications,
      paginatedNotifications,
      submitNotice,
      cancelEdit,
      divisionList,
      selectedDivisions,
      handlePublishTypeChange,
      changeTab,
      createNewNotice,
      editNotification,
      deleteNotification,
      handlePageChange,
    };
  },
};
</script>

<style scoped>
/* 分班选择复选框样式 */
.division-checkboxes {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-left: 10px;
  background-color: #fbfbfb;
  padding: 10px;
  border: 1px solid #ebebeb;
  overflow-y: scroll;
  height: 100px;
  border-radius: 5px;
}

.division-checkbox-label {
  display: flex;
  align-items: center;
  font-size: 16px;
}

/* 富文本编辑器区域样式 */
.editor-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.title-input {
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.publish-options {
  margin-bottom: 10px;
  display: flex;
  align-items: flex-start;
}

.editor-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-button,
.submit-button {
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.cancel-button {
  background-color: #f0f0f0;
  color: #333;
}

.submit-button {
  background-color: #244382;
  color: #fff;
}

.submit-button:hover {
  background-color: #1e3661;
}

.filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.filter button {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
  transition: background-color 0.3s, color 0.3s;
}

.filter button.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}

.filter .create-button {
  margin-left: auto;
  background-color: #244382;
  color: #fff;
  padding: 10px 15px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.filter .create-button:hover {
  background-color: #1e3661;
}

/* 通知列表样式 */
.notification-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  transition: transform 0.3s;
  margin-bottom: 15px;
}

.notification-card:hover {
  transform: translateY(-5px);
  background-color:#f0f0f0;
}

.notification-header {
  display: flex;
  align-items: center;
  gap: 15px;
  position: relative;
}

.badge {
  display: inline-block;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}

/* 分班发布的 Badge 样式 */
.badge-division {
  background-color: #e0f7f9;
  color: #008c9e;
}

/* 统一发布的 Badge 样式 */
.badge-unified {
  background-color: #cae2f9;
  color: #519bd5;
}

.notification-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
  position: absolute;
  right: 0;
  top: 0;
}

.edit-button,
.delete-button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  color: #244382;
  font-size: 14px;
  transition: color 0.3s;
}

.edit-button:hover,
.delete-button:hover {
  color: #1e3661;
}

.notification-card h2 {
  margin: 0;
  font-size: 18px;
}

.notification-card p {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

/* 分班标签样式 */
.division-name {
  background-color: #e0f0e0;
  padding: 3px 5px;
  border-radius: 5px;
  margin-right: 5px;
  font-size: 12px;
}
</style>
